<!-- 添加物料 -->
<template>
  <el-dialog custom-class="material-dialog" title="请选择物料" :visible.sync="showDialog" width="70%" append-to-body="true" @close="closeMaterialDialog">
    <div class="titleBar" v-if="showSection">
      <i class="el-icon-vertical-bar"></i>
      用料工段
    </div>
    <avue-form class="infoForm" v-if="showSection" ref="selectSectionDialogForm" :option="selectSectionOption" v-model="selectSectionDialogForm"></avue-form>
    <div class="titleBar"><i class="el-icon-vertical-bar"></i>物料</div>
    <avue-form ref="materialForm" :option="material.option" v-model="material.form">
      <template slot="menuForm">
        <el-button type="primary" icon="el-icon-search" @click="handleSearchMaterial">搜索</el-button>
        <el-button icon="el-icon-delete" @click="handleClearMaterial">清空</el-button>
      </template>
    </avue-form>
    <avue-crud
      ref="materialCrud"
      :option="material.tableOption"
      :page.sync="material.page"
      :table-loading="material.tableLoading"
      :data="material.tableData"
      @selection-change="selectionMaterialChange"
      @row-click="handleRowClick"
      @current-change="currentMaterialChange"
      @size-change="sizeMaterialChange"
    >
    </avue-crud>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" size="small" icon="el-icon-check" @click="materialSubmit">确 定</el-button>
      <el-button size="small" icon="el-icon-circle-close" @click="materialCancel">取 消</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { getList as getPartMasterList } from '@/api/admin/partmaster';
import { mapGetters, mapState } from 'vuex';
import { addOrUpdate } from '@/api/product/product-material-config';

export default {
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    productInfoList: {
      type: Array,
      default: () => []
    },
    showSection: {
      type: Boolean,
      default: true
    }
  },
  watch: {
    visible: {
      handler(val) {
        this.showDialog = val;
      },
      immediate: true
    }
  },
  data() {
    return {
      showDialog: false,
      selectSectionDialogForm: {},
      selectSectionOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: '用料工段',
            type: 'select',
            span: 8,
            prop: 'sectionId',
            dicData: []
          }
        ]
      },
      // 添加物料
      material: {
        option: {
          submitBtn: false,
          emptyBtn: false,
          menuSpan: 8,
          column: [
            {
              label: '物料编码',
              prop: 'partNo',
              labelWidth: 80,
              span: 8
            },
            {
              label: '物料名称',
              prop: 'name',
              labelWidth: 80,
              span: 8
            }
          ]
        },
        form: {},
        tableOption: {
          height: 400,
          border: true,
          index: true,
          indexLabel: '序号',
          tip: false,
          selection: true,
          addBtn: false,
          refreshBtn: false,
          columnBtn: false,
          menu: false,
          reserveSelection: true,
          selectable: (row, index) => {
            return !this.productInfoList.map((item) => item.partMasterId).includes(row.id);
          },
          column: [
            {
              label: '物料编码',
              prop: 'partNo'
            },
            {
              label: '物料名称',
              prop: 'name'
            },
            {
              label: '物料分类',
              prop: 'categoryName'
            },
            {
              label: '物料规格',
              prop: 'partSpec'
            },
            {
              label: '描述',
              prop: 'description'
            }
          ]
        },
        selectionList: [],
        page: {
          pageSize: 20,
          currentPage: 1,
          total: 0
        },
        tableLoading: false,
        tableData: []
      }
    };
  },
  computed: {
    ...mapGetters(['permission']),
    ...mapState({
      realName: (state) => state.user.userInfo.real_name,
      userId: (state) => state.user.userInfo.user_id
    }),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.workorder_add, false),
        viewBtn: this.vaildData(this.permission.workorder_view, false),
        delBtn: this.vaildData(this.permission.workorder_delete, false),
        editBtn: this.vaildData(this.permission.workorder_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    },
    basicInfoIndex() {
      let indexs = [];
      this.basicInfoSelectionList.forEach((ele) => {
        indexs.push(ele.$index);
      });
      return indexs;
    }
  },
  methods: {
    initData(workSectionList) {
      let data = structuredClone(workSectionList);
      console.log('this.selectSectionOption', this.selectSectionOption);
      let sectionId = this.findObject(this.selectSectionOption.column, 'sectionId');
      sectionId.dicData = this._map(data, (item) => {
        return {
          label: item.sectionName,
          value: item.sectionId
        };
      });
      this.baseGetMaterialData();
    },
    handSelect() {
      this.$refs.crud.setCurrentRow();
    },
    selectionAll() {
      this.$refs.crud.setCurrentRow();
    },
    openPackingConfig() {
      if (this.form.partNo) {
        this.openUserCommonModal({
          type: 'packingConfig'
        });
      } else {
        this.$message({
          type: 'warning',
          message: '请先选择产品编码！'
        });
      }
    },
    closeSubWorkOrderDialog(params) {
      this.workorderSplitVisible = false;
      if (params) {
        this.onLoad(this.page);
        this.$refs.crud.toggleSelection();
      }
    },
    baseGetMaterialData() {
      this.material.page.currentPage = 1;
      this.material.page.pageSize = 15;
      this.getMaterialData();
    },
    // 获取物料列表数据
    getMaterialData() {
      this.material.tableLoading = true;
      getPartMasterList(this.material.page.currentPage, this.material.page.pageSize, this.material.form)
        .then((res) => {
          let data = res.data.data;
          this.$nextTick(() => {
            this.material.tableData = data.records;
            this.material.page.total = data.total;
          });
        })
        .catch((err) => {})
        .finally(() => {
          this.material.tableLoading = false;
        });
    },
    currentMaterialChange(currentPage) {
      this.material.page.currentPage = currentPage;
      this.getMaterialData();
    },
    sizeMaterialChange(pageSize) {
      this.material.page.pageSize = pageSize;
      this.getMaterialData();
    },
    selectionMaterialChange(list) {
      this.material.selectionList = list;
    },
    handleSearchMaterial() {
      this.baseGetMaterialData();
    },
    handleClearMaterial() {
      this.material.form.partNo = '';
      this.material.form.name = '';
      this.baseGetMaterialData();
    },
    handleRowClick(row) {
      console.log('this.productInfoList', this.productInfoList);
      let find = this.productInfoList.map((item) => item.partMasterId).includes(row.id);
      if (!find) {
        this.$refs.materialCrud.toggleRowSelection(row);
      }
    },
    materialSubmit() {
      console.log('this.material.selectionList', this.material.selectionList);
      let sectionId = this.findObject(this.selectSectionOption.column, 'sectionId');
      for (let i = 0; i < this.material.selectionList.length; i++) {
        let rowData = this.material.selectionList[i];
        if (this.showSection) {
          let workSectionObj = this._find(sectionId.dicData, { value: this.selectSectionDialogForm.sectionId });
          this.productInfoList.push({
            $index: this.productInfoList.length,
            partMasterId: rowData.id,
            partNo: rowData.partNo,
            partName: rowData.name,
            partModel: rowData.partModel ? rowData.partModel : '',
            partSpec: rowData.partSpec,
            quantity: undefined,
            sectionId: this.selectSectionDialogForm.sectionId,
            sectionName: workSectionObj ? workSectionObj.label : '',
            partSubType: rowData.partSubType
          });
        } else {
          this.productInfoList.push({
            $cellEdit: true,
            partMasterId: rowData.id,
            partNo: rowData.partNo,
            partName: rowData.name,
            partModel: rowData.partModel ? rowData.partModel : '',
            partSpec: rowData.partSpec,
            quantity: undefined,
            partSubType: rowData.partSubType
          });
        }
      }
      this.showDialog = false;
      this.$emit('update:visible', false);
      this.material.selectionList = [];
      this.$refs.materialCrud.toggleSelection();
    },
    materialCancel() {
      this.closeMaterialDialog();
    },
    closeMaterialDialog() {
      if (this.showSection) {
        this.$refs.selectSectionDialogForm.resetFields();
        this.selectSectionDialogForm = {};
      }
      this.material.selectionList = [];
      this.$refs.materialCrud.toggleSelection();
      this.material.form.partNo = '';
      this.material.form.name = '';
      this.showDialog = false;
      this.$emit('update:visible', false);
    }
  }
};
</script>

<style lang="scss" scoped>
::v-deep .material-dialog {
  margin-top: 5vh !important;
  .el-dialog__body {
    padding: 15px 20px;
    .titleBar {
      margin-bottom: 10px;
      font-weight: bold;
    }
    .infoForm {
      .avue-form__group {
        .el-col {
          &:last-child {
            display: none;
          }
        }
      }
    }
    .avue-crud__menu {
      display: none;
    }
  }
}
</style>
